package VisitServlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//@WebServlet("/visit")
public class VisitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        // 获取所有Cookie
        Cookie[] cookies = request.getCookies();
        Date lastVisitTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 检查是否存在名为"lastVisit"的Cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("lastVisit".equals(cookie.getName())) {
                    lastVisitTime = new Date(Long.parseLong(cookie.getValue()));
                    break;
                }
            }
        }

        // 创建新的Cookie来存储当前访问时间
        Date currentTime = new Date();
        Cookie lastVisitCookie = new Cookie("lastVisit", String.valueOf(currentTime.getTime()));
        lastVisitCookie.setMaxAge(60 * 60 * 24); // 设置Cookie存活时间为24小时
        response.addCookie(lastVisitCookie);

        // 构建响应内容
        StringBuilder content = new StringBuilder();
        content.append("<html><body><h1>访问信息</h1>");
        if (lastVisitTime == null) {
            content.append("<p>您是第一次访问本网站。</p>");
        } else {
            content.append("<p>您上次访问时间：").append(sdf.format(lastVisitTime)).append("</p>");
        }
        content.append("<p>本次访问时间：").append(sdf.format(currentTime)).append("</p>");
        content.append("</body></html>");

        // 输出响应内容
        response.getWriter().write(content.toString());
    }
}